package com.hhhn.wk.main.tab4.allorder.fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.base.BaseFragment;
import com.hhhn.wk.config.Config;
import com.hhhn.wk.main.tab4.allorder.activity.StarSendGoosActivity;
import com.hhhn.wk.main.tab4.allorder.activity.StartPaymentActivity;
import com.hhhn.wk.main.tab4.allorder.adapter.ParentAdapter;
import com.hhhn.wk.main.tab4.allorder.entity.ItemGoodsBean;

import com.hhhn.wk.main.tab4.allorder.entity.MyOrder;
import com.hhhn.wk.pay.PayActivity;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.ToastUtils;
import com.hhhn.wk.widget.adapter.MyAdaper;
import com.hhhn.wk.widget.adapter.ViewHolder;
import com.hhhn.wk.widget.wkpulltorefreshlayout.BaseRefreshListener;
import com.hhhn.wk.widget.wkpulltorefreshlayout.PullToRefreshLayout;
import com.hhhn.wk.widget.wkpulltorefreshlayout.ViewStatus;
import com.hhhn.wk.widget.wkpulltorefreshlayout.util.DisplayUtil;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import static android.content.ContentValues.TAG;

/**
 * * * * * * * * * * * *
 * @author：文珂 ｡◕‿◕｡ *
 * Data：2018/1/2 0002    ｡◕‿◕｡ *
 * Function：      ｡◕‿◕｡ *
 * 待发货
 * * * * * * * * * * *
 */
public class Order03Fragment extends BaseFragment {
    /*listView*/
    private ListView mLoadListView;
    private PullToRefreshLayout mPullToRefreshLayout;
    public static ArrayList<MyOrder> mArrayList = new ArrayList<MyOrder>();
//    private static MyAdaper<MyOrder> mAdapter;
    private ParentAdapter parentAdapter;
    List<ItemGoodsBean> orderDetailVoList;//商品数组
    private int page = 1;
    private int refresh = 0;//0 第一次进入  1下拉刷新  2上啦加载
    private boolean isWU = false;
    private Context context;
    BaseActivity activity;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (mArrayList.size() == 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        loadData();
                    }
                    break;
                case 2:
                    mPullToRefreshLayout.showView(ViewStatus.EMPTY_STATUS);////空数据
                    break;
                case 3:
                    mPullToRefreshLayout.showView(ViewStatus.ERROR_STATUS);////网络错误
                    break;
            }
            super.handleMessage(msg);
        }
    };
    public Order03Fragment() {
        // Required empty public constructor
    }
    @Override
    protected void initView(View mRootView) {
        context = getContext();
        activity = (BaseActivity) getActivity();

        mLoadListView = mRootView.findViewById(R.id.mLoadListView);
        mPullToRefreshLayout = mRootView.findViewById(R.id.activity_list);
        mLoadListView.setDivider(new ColorDrawable(getResources().getColor(R.color.white)));
        mLoadListView.setDividerHeight(DisplayUtil.dp2Px(getActivity(), 4));
    }
    @Override
    protected void initData() {
        getJSON();
    }
    @Override
    protected void initClick() {
        mPullToRefreshLayout.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                refresh = 1;
                page = 1;
                orderDetailVoList.clear();
                mArrayList.clear();
                if (parentAdapter != null) {
                    parentAdapter.notifyDataSetChanged();
                }
                isWU = false;
                getJSON();
            }

            @Override
            public void loadMore() {
                if (isWU) {
                    ToastUtils.showShortToast(context, "暂无更多");
                    mPullToRefreshLayout.showView(ViewStatus.CONTENT_END);//暂无更多
                } else {
                    refresh = 2;
                    page++;
//                    if (parentAdapter != null) {
//                        parentAdapter.notifyDataSetChanged();
//                    }
                    getJSON();
                }
            }
        });
//        mLoadListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
////                Intent intent = new Intent(context, StarSendGoosActivity.class);
////                intent.putExtra("id",mArrayList.get(i).getId());
////                startActivity(intent);
////                Log.d(TAG, "onItemClick: "+mArrayList.get(i).getId());
//            }
//        });
    }
    @Override
    protected int setLayoutResouceId() {
        return R.layout.fragment_order02;
    }
    private void getJSON() {
        mPullToRefreshLayout.showView(ViewStatus.LOADING_STATUS);//加载中
        RequestParams params = AllPublic.getParamsProductOrder(activity, "/allOrderInfo", false);
        params.addParameter("cmUserId", activity.getUser().getUid());
        params.addParameter("currentPage",page);
        params.addParameter("pageSize",Config.ROWS);
//        orderStatus	订单状态
//      0全部  103504：待发货    103501：待发货   103502：待收货/已发货   103503：待评价
        params.addParameter("orderStatus", 103501);
        Log.d("@@", "params: " + params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("待发货", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {//成功
//                        JSONObject data = jsonObject.getJSONObject("data");
                        JSONArray records = jsonObject.getJSONArray("data");
                        if (records.length() < Config.ROWS) {
                            isWU = true;
                        }
                        MyOrder myOrder = null;
                        ItemGoodsBean mItemGoodsBean;

                        for (int i = 0; i < records.length(); i++) {

                            JSONObject object = records.getJSONObject(i);
                            String id = object.has("id") ? object.getString("id") : "";//id
                            String orderid = object.has("orderCode") ? object.getString("orderCode") : "";//订单编号

                            int order_status = object.has("orderStatus") ? object.getInt("orderStatus") : 0;//订单状态
                            int order_type = object.has("orderType") ? object.getInt("orderType") : 0;//是否维权订单
                            String cmIndate = object.has("cmIndate") ? object.getString("cmIndate") : "";//创建时间

                            String money = object.has("money") ? object.getString("money") : "";//结算价格（	需要支付金额）
                            String deductibleAmount = object.has("deductibleAmount") ? object.getString("deductibleAmount") : "";//抵扣金额
                            String actualPayment = object.has("orderJs") ? object.getString("orderJs") : "";//实际

                            myOrder = new MyOrder();
                            myOrder.setId(id);
                            myOrder.setDeductibleAmount(deductibleAmount);
                            myOrder.setActualPayment(actualPayment);
                            myOrder.setOrder_codeId(orderid);
                            myOrder.setOrder_time(cmIndate);
                            myOrder.setOrder_money(money);
                            myOrder.setOrder_type(order_type);
                            myOrder.setOrder_status(order_status);
                            JSONArray productInfo = object.getJSONArray("productInfo");
                            orderDetailVoList = new ArrayList<ItemGoodsBean>();//商品数组
                            for (int j = 0; j < productInfo.length(); j++) {
                                mItemGoodsBean = new ItemGoodsBean();
                                JSONObject sBean = productInfo.getJSONObject(j);
                                String product_name = sBean.has("name") ? sBean.getString("name") : "";//商品名称
                                int product_nums = sBean.has("productNums") ? sBean.getInt("productNums") : 0;//商品数量
                                String product_picture = sBean.has("productPicture") ? sBean.getString("productPicture") : "";//商品图片
                                String price_js = sBean.has("priceJs") ? sBean.getString("priceJs") : "";//商品结算（商户看见的商品单价）
                                mItemGoodsBean.setGoodsMoney(price_js);
                                mItemGoodsBean.setGoodsName(product_name);
                                mItemGoodsBean.setGoodsNumber(product_nums);
                                mItemGoodsBean.setGoodsImg(product_picture);
//                                Log.d("解析", "名称: "+product_name);
                                orderDetailVoList.add(mItemGoodsBean);
                            }
                            myOrder.setBeanGoodsList(orderDetailVoList);
//                            Log.d("验证填入", "onSuccess: "+myOrder.toString());
                            mArrayList.add(myOrder);

                        }
                        handler.sendEmptyMessage(1);
                    } else {
                        Toast.makeText(getActivity(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(3);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("待发货-第二个", ex + "");
                ex.printStackTrace();
                handler.sendEmptyMessage(3);
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("待发货-第三个", cex + "");
            }

            @Override
            public void onFinished() {
                Log.d("待发货-第四个", "onFinished");
            }
        });
    }

    private void loadData() {
        if (parentAdapter==null){
            parentAdapter = new ParentAdapter(mArrayList, context);
            mLoadListView.setAdapter(parentAdapter);
        }else {
            parentAdapter.notifyDataSetChanged();
        }

        if (refresh == 1) {
            mPullToRefreshLayout.finishRefresh();//下拉刷新
        } else if (refresh == 2) {
            mPullToRefreshLayout.finishLoadMore();//上啦加载
        }
        mPullToRefreshLayout.showView(ViewStatus.CONTENT_STATUS);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mArrayList != null) {
            mArrayList.clear();
        }
        if (orderDetailVoList != null) {
            orderDetailVoList.clear();
        }
        if (parentAdapter != null) {
            parentAdapter = null;
        }
    }
    private void upView(){
        if (mArrayList != null) {
            mArrayList.clear();
        }
        if (orderDetailVoList != null) {
            orderDetailVoList.clear();
        }
        if (parentAdapter != null) {
            parentAdapter = null;
        }
        getJSON();
    }
}
